const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = 3000;
const DATA_FILE = path.join(__dirname, 'data.json');

app.use(cors());
app.use(express.json());
// 查询
app.get('/homonyms', async (req, res) => {
  try {
    const json = await fs.readFile(DATA_FILE, 'utf-8');
    res.json(JSON.parse(json));
  } catch (err) {
    console.error('Read data.json failed:', err);
    res.status(500).json({ message: 'Failed to read data' });
  }
});
// 新增
app.post('/homonyms', async (req, res) => {
  try {
    const { homonym, realWord } = req.body;
    if (!homonym || !realWord) {
      return res.status(400).json({ message: '同音词和实际词不能为空' });
    }

    const json = await fs.readFile(DATA_FILE, 'utf-8');
    const data = JSON.parse(json);
    
    // 检查是否已存在相同的同音词
    const exists = data.some(item => item.homonym === homonym);
    if (exists) {
      return res.status(400).json({ message: '该同音词已存在，请使用不同的同音词' });
    }
    
    // 在数组开头插入新数据
    data.unshift({ homonym, realWord });
    
    await fs.writeFile(DATA_FILE, JSON.stringify(data, null, 2), 'utf-8');
    res.json({ message: '新增成功', data: { homonym, realWord } });
  } catch (err) {
    console.error('Write data.json failed:', err);
    res.status(500).json({ message: 'Failed to write data' });
  }
});

// 编辑
app.put('/homonyms', async (req, res) => {
  try {
    const { oldHomonym, oldRealWord, homonym, realWord } = req.body;
    if (!oldHomonym || !oldRealWord || !homonym || !realWord) {
      return res.status(400).json({ message: '参数不完整' });
    }

    const json = await fs.readFile(DATA_FILE, 'utf-8');
    let data = JSON.parse(json);
    
    // 查找要编辑的数据
    const index = data.findIndex(item => 
      item.homonym === oldHomonym && item.realWord === oldRealWord
    );
    
    if (index === -1) {
      return res.status(404).json({ message: '未找到要编辑的数据' });
    }
    
    // 如果同音词有变化，检查是否与其他数据重复
    if (homonym !== oldHomonym) {
      const exists = data.some((item, i) => i !== index && item.homonym === homonym);
      if (exists) {
        return res.status(400).json({ message: '该同音词已存在，请使用不同的同音词' });
      }
    }
    
    data[index] = { homonym, realWord };
    
    await fs.writeFile(DATA_FILE, JSON.stringify(data, null, 2), 'utf-8');
    res.json({ message: '编辑成功' });
  } catch (err) {
    console.error('Update data failed:', err);
    res.status(500).json({ message: 'Failed to update data' });
  }
});
// 删除
app.delete('/homonyms', async (req, res) => {
  try {
    const { homonym, realWord } = req.body;
    if (!homonym || !realWord) {
      return res.status(400).json({ message: '同音词和实际词不能为空' });
    }

    const json = await fs.readFile(DATA_FILE, 'utf-8');
    let data = JSON.parse(json);
    
    // 过滤掉匹配的数据
    const newData = data.filter(item => 
      item.homonym !== homonym || item.realWord !== realWord
    );
    
    if (newData.length === data.length) {
      return res.status(404).json({ message: '未找到要删除的数据' });
    }
    
    await fs.writeFile(DATA_FILE, JSON.stringify(newData, null, 2), 'utf-8');
    res.json({ message: '删除成功' });
  } catch (err) {
    console.error('Delete data failed:', err);
    res.status(500).json({ message: 'Failed to delete data' });
  }
});

// 批量导入
app.post('/homonyms/batch', async (req, res) => {
  try {
    const { items } = req.body;
    if (!Array.isArray(items) || items.length === 0) {
      return res.status(400).json({ message: '导入数据不能为空' });
    }

    const json = await fs.readFile(DATA_FILE, 'utf-8');
    const data = JSON.parse(json);
    
    // 统计结果
    let successCount = 0;
    let skipCount = 0;
    const errors = [];
    
    // 遍历待导入数据
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      const { homonym, realWord } = item;
      
      // 验证数据
      if (!homonym || !realWord) {
        errors.push(`第${i + 1}行: 同音词和实际词不能为空`);
        continue;
      }
      
      // 检查是否已存在
      const exists = data.some(d => d.homonym === homonym);
      if (exists) {
        skipCount++;
        continue;
      }
      
      // 添加到数据中
      data.push({ homonym, realWord });
      successCount++;
    }
    
    // 保存数据
    await fs.writeFile(DATA_FILE, JSON.stringify(data, null, 2), 'utf-8');
    
    res.json({ 
      message: '导入完成',
      successCount,
      skipCount,
      errorCount: errors.length,
      errors
    });
  } catch (err) {
    console.error('Batch import failed:', err);
    res.status(500).json({ message: 'Failed to import data' });
  }
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
